package com.stream.populationcheck;

import android.app.AlertDialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    String U = "";
    boolean isOpen = true;
    boolean Open = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        NotificationChannel notificationchannel = new NotificationChannel("002", "通知", NotificationManager.IMPORTANCE_HIGH);
        notificationchannel.setDescription("通知");
        NotificationManager notificationManage = getSystemService(NotificationManager.class);
        notificationManage.createNotificationChannel(notificationchannel);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Handler handler = new Handler(Looper.getMainLooper());

        LineChart chart = findViewById(R.id.chart);
        TextView textview = findViewById(R.id.textView);
        dialog();

        textview.setText("无数据");

        // 准备数据
        List<Entry> entries = new LinkedList<>();
        HttpGetRequest Response = new HttpGetRequest();


        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true) {

                    if (U.equals("")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 在这里执行UI操作，比如创建对话框
                                dialog(); // 你的对话框创建方法
                            }
                        });
                    }

                    try {
                        Response.getValue(U);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (Response.state == 0) {
                        Wrong(Response, handler);
                    }

                    if (Response.value == 0) {
                        continue;
                    }

                    entries.add(new Entry(0, Response.value));

                    if (entries.size() > 20) {
                        entries.remove(0);
                    }

                    int i = 0;
                    for (Entry entry : entries) {
                        entry.setX(i);
                        i++;
                    }

                    LineDataSet dataSet = new LineDataSet(entries, "当前人数"); // Label为该数据集的描述，会显示在图例中
                    dataSet.setColor(Color.RED); // 设置线条颜色
                    dataSet.setValueTextColor(Color.BLUE); // 设置数据值文字颜色

                    LineData lineData = new LineData(dataSet);
                    chart.setData(lineData);

                    YAxis YAxis_left = chart.getAxisLeft();
                    YAxis_left.setAxisMinimum(0); // 设置Y轴最小值为0
                    float number_max = dataSet.getYMax() + 5;
                    YAxis_left.setAxisMaximum(number_max); // 设置Y轴最小值为0

                    YAxis YAxis_right = chart.getAxisRight();
                    YAxis_right.setAxisMinimum(0);
                    YAxis_right.setAxisMaximum(number_max);

                    Description description = new Description();
                    description.setText("");
                    chart.setDescription(description);


                    chart.invalidate();

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            textview.setText("当前人数：" + Response.value);
                        }
                    });

                    if (Response.value >= 60) {
                        notification(Response.value);
                    }

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void dialog() {
        if (Open) {
            return;
        }
        Open = true;
        // 创建一个编辑文本框
        final EditText editText = new EditText(MainActivity.this);

        // 创建一个 AlertDialog.Builder 对象
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("请输入IP地址和端口号。"); // 设置对话框标题
        builder.setView(editText); // 设置对话框的视图为编辑文本框

        // 设置对话框的积极按钮
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 在这里处理用户点击确认按钮后的逻辑
                String userInput = editText.getText().toString();
                // 处理用户输入的内容
                U = "http://" + userInput + "/population";
                Open = false;
            }
        });

        // 创建并显示对话框
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    private void Wrong(HttpGetRequest infoResponse, Handler handler) {
        try {
            infoResponse.getValue(U);
        } catch (IOException e) {
            e.printStackTrace();
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "没有发现数据！", Toast.LENGTH_SHORT).show();
            }
        });
        while (infoResponse.value == 0) {
            try {
                Thread.sleep(1000);
                try {
                    infoResponse.getValue(U);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void notification(int value) {
        if (!isOpen) {
            return;
        }
        Random random = new Random(); //随机数选取器
        //构造一般通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "002")
                .setContentTitle("请注意！人数过多！")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentText("请注意，现在系统检测到人数过多，当前人数为" + value);
        //显示一般通知
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(random.nextInt(10000), builder.build());
        isOpen = false;
    }

    class HttpGetRequest {

        int state;
        int value;

        // 发起GET请求并返回整数值
        public void getValue(String urlString) throws IOException {
            // 创建URL对象
            URL url = new URL(urlString);

            // 创建HTTP连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");

            try {
                // 连接并获取响应
                urlConnection.connect();
                int responseCode = urlConnection.getResponseCode();

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 读取响应
                    InputStream inputStream = urlConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        response.append(line);
                    }
                    bufferedReader.close();

                    state = 1;
                    // 将响应转换为整数值
                    value = Integer.parseInt(response.toString().trim());
                } else {
                    // 如果服务器返回错误
                    state = 0;
                }
            } finally {
                // 关闭连接
                urlConnection.disconnect();
            }
        }


    }
}